package com.hsapp.model;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.databinding.DataBindingUtil;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;

import com.hsapp.R;
import com.hsapp.activity.BaseActivity;
import com.hsapp.activity.SBDetailActivity;
import com.hsapp.adapter.GridSBAdapter;
import com.hsapp.bean.SBDetailBean;
import com.hsapp.bean.SBSaveBean;
import com.hsapp.bean.UpImgBean;
import com.hsapp.bean.WjsBean;
import com.hsapp.databinding.ActivitySbdetailBinding;
import com.hsapp.http.MNetHttp;
import com.hsapp.listener.GralleryImgListener;
import com.hsapp.listener.HttpListener;
import com.hsapp.listener.UpImageListener;
import com.hsapp.util.GralleryImgUtil;
import com.hsapp.util.PreferencesUtil;
import com.hsapp.util.Static;

import org.greenrobot.eventbus.EventBus;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.hsapp.R.id.submit;

/**
 * Created by apple on 2018/3/7.
 */

public class SBDetailModel extends BaseModel{
    private SBDetailBean bean;
    private GridSBAdapter adapter;
    private List<String> adapterData,delimglist;
    private ActivitySbdetailBinding binding;
    private Map<String,String> upFile,params,delparams;
    private int selectImg=0,count=0;
    private boolean isEdit = false,isSubmit=false;//判断是否提交成功过
    public android.support.v7.app.AlertDialog.Builder deldialog,isSubmitDialog,closeDialog;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 200:
                    count=count-1;
                    if(count==0){
                        upSB();
                    }
                    /*progressDialog.dismiss();
                    adapterData.remove(selectImg);
                    adapter.notifyDataSetChanged();*/
                    break;
                case 404:
                    progressDialog.dismiss();
                    Static.showToast(context,"删除图片不存在");
                    break;
                case 500:
                    progressDialog.dismiss();
                    Static.showToast(context,"删除失败");
                    break;
            }
        }
    };

    public SBDetailModel(final Context context){
        super(context);

        binding= DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.activity_sbdetail,null,false);
        bean=(SBDetailBean)((SBDetailActivity)context).getIntent().getSerializableExtra("data");
        binding.setData(bean);
        binding.setClick(new ViewClick());
        binding.setIsEdit(isEdit);
        upFile=new HashMap<String,String>();
        params=new HashMap<String,String>();
        delparams=new HashMap<String,String>();
        delimglist=new ArrayList<String>();
        deldialog = new android.support.v7.app.AlertDialog.Builder(context);
        deldialog.setCancelable(true);
        deldialog.setTitle("提示");
        deldialog.setMessage("确定要删除这张照片吗？");
        deldialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                if(adapterData.get(selectImg).contains("http://")){
                    //delImg(selectImg);
                    adapterData.remove(selectImg);
                    adapter.notifyDataSetChanged();
                    delimglist.add(bean.getWjs().get(selectImg).getZj());
                }else{
                    adapterData.remove(selectImg);
                    adapter.notifyDataSetChanged();
                }
            }
        });

        isSubmitDialog = new android.support.v7.app.AlertDialog.Builder(context);
        isSubmitDialog.setCancelable(true);
        isSubmitDialog.setTitle("提示");
        isSubmitDialog.setMessage("确定要修改吗？");
        isSubmitDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                submit();

            }
        });

        closeDialog = new android.support.v7.app.AlertDialog.Builder(context);
        closeDialog.setCancelable(true);
        closeDialog.setTitle("提示");
        closeDialog.setMessage("确定要取消修改吗？");
        closeDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                isEdit=false;
                for(int row=adapterData.size()-1;row>=0;row--){
                    if(!(adapterData.get(row).contains("http://"))){
                        adapterData.remove(row);
                    }
                }
                setStatus();
                binding.x.setText(((Activity)context).getString(R.string.x)+bean.getX());
                binding.y.setText(((Activity)context).getString(R.string.y)+bean.getY());

            }
        });

        initAdapter();

    }

    public ActivitySbdetailBinding getBinding(){
        return binding;
    }

    public boolean getIsEdit(){
        return isEdit;
    }

    public boolean getIsSubmit(){
        return isSubmit;
    }



    private void initAdapter(){
        adapterData=new ArrayList<String>();
        if(!(bean.getWjs()==null||bean.getWjs().size()==0)){
            //adapterData.addAll(bean.getWjs())
            for(WjsBean b:bean.getWjs()){
                adapterData.add(Static.imgurl+b.getFilepath()+"/"+b.getZj()+b.getPostfix());
            }

        }
        adapter=new GridSBAdapter(context,adapterData);
        binding.gridView.setAdapter(adapter);
        adapter.setIsEdit(isEdit);
        binding.gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if(adapter.getIsEdit()&&i==adapterData.size()){
                    GralleryImgUtil.getInstance(context, new GralleryImgImpl()).showImgList();
                }
            }
        });
        binding.gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                if(adapter.getIsEdit()&&i!=adapterData.size()){
                    selectImg=i;
                    deldialog.show();
                }
                return false;
            }
        });

    }

    class GralleryImgImpl implements GralleryImgListener {

        @Override
        public void success(String filepath) {
            adapterData.add(filepath);
            adapter.notifyDataSetChanged();
        }

        @Override
        public void fail(String msg) {

        }
    }

    public void submit(){
        boolean isAdd = false;
        for(String data:adapterData){
            if (!(data.contains("http://"))){
                isAdd=true;
            }
        }
        progressDialog.show();
        if(isAdd){
            upfile();
        }else {
            if(delimglist.size()>0){
                delImg();
            }else{
                upSB();
            }

        }
    }

    public class ViewClick{
        public void onClick(View view){
            switch (view.getId()){
                case submit:
                    isEdit=!isEdit;

                    //adapter.setIsEdit(isEdit);
                    if(isEdit){

                        setStatus();
                       // binding.setIsEdit(isEdit);
                    }else{
                        isSubmitDialog.show();

                    }


                    //binding.setIsEdit(true);

                break;
                case R.id.localbtn:
                    if(((BaseActivity)context).Xlocation==0||((BaseActivity)context).Ylocation==0){
                        Static.showToast(context,"gps获取失败，请空旷的室外");
                    }else{
                        Static.showToast(context,"定位成功");
                        binding.x.setText(context.getText(R.string.x)+new DecimalFormat("#.000000").format(((BaseActivity)context).Xlocation));
                        binding.y.setText(context.getText(R.string.y)+new DecimalFormat("#.000000").format(((BaseActivity)context).Ylocation));
                    }
                    break;
            }

        }
    }

    private void upfile(){

        upFile.put("cjr", PreferencesUtil.getInstance(context).getLoginSFZH());
        upFile.put("cjsbzj",bean.getZj());
        MNetHttp.getInstance().rxUpBitmapList(Static.UPIMAGE,adapterData,upFile,UpImgBean.class,new ImgUpResult());

    }
    private void upSB(){
        String x=binding.x.getText().toString().replaceAll(context.getString(R.string.x),"");
        String y=binding.y.getText().toString().replaceAll(context.getString(R.string.y),"");
        params.put("x",x);
        params.put("y",y);
        params.put("zj",bean.getZj());
        MNetHttp.getInstance().rxPostRequest(Static.SAVESB,params,SBSaveBean.class,new SaveResult());

    }

    public void delImg(){
        count = delimglist.size();
        //progressDialog.show();
        if(count==0){
            upSB();
        }else{
            for (String zj:delimglist){
                delparams.put("zj",zj);
                MNetHttp.getInstance().postRequest(Static.DelImg,delparams,new HttpListener(){

                    @Override
                    public void success(Object obj) {

                        if(((String)obj).equals("200")){
                            handler.sendEmptyMessage(200);

                        }else if((((String)obj).equals("404"))){
                            handler.sendEmptyMessage(404);

                        }else{
                            handler.sendEmptyMessage(500);

                        }

                    }

                    @Override
                    public void fail(String msg) {
                        progressDialog.dismiss();
                        Static.showToast(context,msg);
                    }
                });
            }
        }


    }

    class ImgUpResult implements UpImageListener {

        @Override
        public void start() {

        }

        @Override
        public void success(Object obj) {
            if(((String)obj).equals("200")){
                delImg();

            }else {
                Static.showToast(context,"上传失败，请重试");
                progressDialog.dismiss();
            }
        }

        @Override
        public void failure(String msg) {
            Static.showToast(context,msg);
            progressDialog.dismiss();
            isEdit=true;
            setStatus();
        }

        @Override
        public void complete() {

        }
    }

    class SaveResult implements HttpListener{

        @Override
        public void success(Object obj) {
            progressDialog.dismiss();
            if(((SBSaveBean)obj).getType().equals("2")){
                Static.showToast(context,"修改成功");

                setStatus();
                isSubmit=true;
            }else{
                isEdit=true;
                setStatus();
                Static.showToast(context,"修改失败");
            }
        }

        @Override
        public void fail(String msg) {
            Static.showToast(context,msg);
            progressDialog.dismiss();
            isEdit=true;
            setStatus();
        }
    }

    private void setStatus(){
        binding.setIsEdit(isEdit);
        adapter.setIsEdit(isEdit);
        ((SBDetailActivity)context).IsEdit(isEdit);
    }

    public void onDestroy(){
        EventBus.getDefault().unregister(this);
    }
}
